package com.lly.songhigh.activity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.RecentSearchAdapter;
import com.lly.songhigh.adapter.SearchBlurListViewAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.Search;
import com.lly.songhigh.entity.SearchBlur;
import com.lly.songhigh.entity.SearchPlay;
import com.lly.songhigh.entity.dao.RecentSearch;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.fragment.SearchResultFragment;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.utils.SharedPreferencesUtils;
import com.lly.songhigh.view.EditTextWithDel;
import com.lly.songhigh.volley.StringRequestUtf;
import com.lly.songhigh.volley.VolleySingleton;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/21.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, RecentSearchAdapter.OnItemDeleteListener {


    private Toolbar searchToolbar;
    private ImageView searchSearch;
    private EditTextWithDel searchEdit;
    private View searchEditLine;
    private GridView searchGridview;
    private TextView searchHotSearch;
    private FrameLayout searchBelow;
    private ImageView searchToolbarBack;
    private ListView searchBlurListView;
    private LinearLayout searchBelowHistory;
    private List<Search.DataEntity> datas;
    private List<String> singers;
    private String endUrl;
    private String editText;
    private SearchResultFragment searchResultFragment;
    private Handler handler = new Handler();
    private String startUrl = URL.SEARCH_BLUR;
    private VolleySingleton volleySingleton;
    private List<MusicInfo> musicInfos;
    private DaoSingleton daoSingleton;
    private List<SearchBlur.DataEntity.SongEntity> songEntities;
    private List<RecentSearch> recentSearches;
    private ListView recentSearchList;
    private TextView clearSearchHistory;
    private RecentSearchAdapter adapter;
    private RecentSearch recentSearch;
    private FragmentManager manager;
    private FragmentTransaction transaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        BaseApplication.getInstance().addActivity(this);
        daoSingleton = DaoSingleton.getInstance();
        initView();
        initData();
    }

    //热门搜索
    private void initData() {
        volleySingleton = VolleySingleton.getInstance();
        singers = new ArrayList<>();
        StringRequestUtf stringRequestUtf = new StringRequestUtf(URL.SEARCH_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                searchHotSearch.setVisibility(View.VISIBLE);
                searchGridview.setVisibility(View.VISIBLE);
                Gson gson = new Gson();
                Search search = gson.fromJson(response, Search.class);
                datas = search.getData();
                for (Search.DataEntity data : datas) {
                    singers.add(data.getVal());
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<>(SearchActivity.this, R.layout.hot_search, R.id.search_singer_tv, singers);
                searchGridview.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(stringRequestUtf);
        recentSearches = daoSingleton.getRecentSearch();
        adapter = new RecentSearchAdapter(recentSearches, this);
        adapter.setOnItemDeleteListener(this);
        recentSearchList.setAdapter(adapter);
        recentSearchList.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (recentSearches != null && recentSearches.size() > 0)
            clearSearchHistory.setVisibility(View.VISIBLE);
        else
            clearSearchHistory.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        endUrl = searchEdit.getText().toString();
        try {
            //将输入转换成utf-8
            endUrl = URLEncoder.encode(endUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        switch (v.getId()) {
            case R.id.search_search: // 搜索按钮
                //不等于空,加入到搜索历史
                if (!searchEdit.getText().toString().isEmpty()) {
                    recentSearch = new RecentSearch(searchEdit.getText().toString());
                    if (daoSingleton.getRecentSearchByTag(searchEdit.getText().toString()).size() == 0) {
                        daoSingleton.getRecentSearchDao().insert(recentSearch);
                    }
                    SharedPreferencesUtils.putSharePre(SearchActivity.this, "SearchActivityEditText", "endUrl", endUrl);
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction transaction = manager.beginTransaction();
                    transaction.replace(R.id.search_below, searchResultFragment);
                    transaction.commit();
                }
                break;

            case R.id.search_toolbar_back:
                finish();
                break;

            case R.id.clear_search_history:
                daoSingleton.deleteRecentSearchAll();
                clearSearchHistory.setVisibility(View.GONE);
                adapter.deleteAll();
                break;
            default:
                break;
        }
    }

    private void initView() {
        searchToolbar = (Toolbar) findViewById(R.id.search_toolbar);
        searchSearch = (ImageView) findViewById(R.id.search_search);
        searchEdit = (EditTextWithDel) findViewById(R.id.search_edit);
        searchEditLine = findViewById(R.id.search_edit_line);
        searchGridview = (GridView) findViewById(R.id.search_gridview);
        searchHotSearch = (TextView) findViewById(R.id.search_hot_search);
        searchBelow = (FrameLayout) findViewById(R.id.search_below);
        searchToolbarBack = (ImageView) findViewById(R.id.search_toolbar_back);
        searchBlurListView = (ListView) findViewById(R.id.search_blur_listView);
        searchBelowHistory = (LinearLayout) findViewById(R.id.search_below_history);
        recentSearchList = (ListView) findViewById(R.id.recent_search_list);
        clearSearchHistory = (TextView) findViewById(R.id.clear_search_history);

        searchGridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        setSupportActionBar(searchToolbar);
        searchResultFragment = new SearchResultFragment();
        searchToolbarBack.setOnClickListener(this);
        searchGridview.setOnItemClickListener(this);
        searchEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    searchSearch.setVisibility(View.VISIBLE);
                    searchEditLine.setBackgroundColor(0xffffffff);
                } else {
                    searchSearch.setVisibility(View.GONE);
                    searchEditLine.setBackgroundColor(0xb7c6c6c6);
                }
            }
        });
        TextChanged();
        searchGridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        searchSearch.setOnClickListener(this);
        searchToolbarBack.setOnClickListener(this);
        clearSearchHistory.setOnClickListener(this);
        searchToolbarBack.setOnClickListener(this);
        recentSearchList.setOnItemClickListener(this);
        searchGridview.setOnItemClickListener(this);
        searchBlurListView.setOnItemClickListener(this);
    }

    /**
     * 监测文本框文字改变
     */
    private void TextChanged() {
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction transaction = manager.beginTransaction();
                    transaction.remove(searchResultFragment);
                    transaction.commit();
                    searchBelowHistory.setVisibility(View.VISIBLE);
                    searchSearch.setVisibility(View.GONE);
                } else {
                    searchBelowHistory.setVisibility(View.GONE);
                    searchSearch.setVisibility(View.VISIBLE);
                }
                handler.post(editChanged);
            }
        });
    }

    /**
     * 文本框数据改变开启线程
     */
    Runnable editChanged = new Runnable() {
        @Override
        public void run() {
            String endUrl = searchEdit.getText().toString();
            try {
                endUrl = URLEncoder.encode(endUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String url = startUrl + endUrl;
            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    SearchBlur searchBlur = gson.fromJson(response, SearchBlur.class);
                    songEntities = searchBlur.getData().getSong();
                    SearchBlurListViewAdapter searchBlurListViewAdapter = new SearchBlurListViewAdapter
                            (SearchActivity.this, songEntities);
                    searchBlurListView.setAdapter(searchBlurListViewAdapter);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(request);
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.search_gridview: // 热词搜索
                String tag = (String) parent.getItemAtPosition(position);
                recentSearch = new RecentSearch(tag);
                if (daoSingleton.getRecentSearchByTag(tag).size() == 0) {
                    daoSingleton.getRecentSearchDao().insert(recentSearch);
                }
                searchEdit.setText(tag);
                try {
                    endUrl = URLEncoder.encode(tag, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                SharedPreferencesUtils.putSharePre(SearchActivity.this, "SearchActivityEditText", "endUrl", endUrl);
                manager = getSupportFragmentManager();
                transaction = manager.beginTransaction();
                transaction.replace(R.id.search_below, searchResultFragment);
                transaction.commit();
                break;
            case R.id.search_blur_listView: // 实时搜索
                musicInfos = new ArrayList<>();
                SearchBlur.DataEntity.SongEntity songEntity = (SearchBlur.DataEntity.SongEntity) parent.getItemAtPosition(position);
                String name = songEntity.getName();
                recentSearch = new RecentSearch(name);
                if (daoSingleton.getRecentSearchByTag(name).size() == 0) {
                    daoSingleton.getRecentSearchDao().insert(recentSearch);
                }
                String url = URL.BLUR_SEARCH_PLAY_START + songEntity.get_id() + URL.BLUR_SEARCH_PLAY_END;
                StringRequestUtf stringRequestUtf = new StringRequestUtf
                        (url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Gson gson = new Gson();
                                SearchPlay searchPlay = gson.fromJson(response, SearchPlay.class);
                                MusicInfo musicInfo = new MusicInfo();
                                musicInfo.setResouce(StringResouce.RESOUCE_NET);
                                musicInfo.setUrl(searchPlay.getData().getUrlList().get(0).getUrl());
                                musicInfo.setSingerName(searchPlay.getData().getSingerName());
                                musicInfo.setSongName(searchPlay.getData().getName());
                                musicInfo.setSingerId(searchPlay.getData().getSingerId());
                                musicInfo.setSongId(searchPlay.getData().getSongId());
                                musicInfo.setDuration(searchPlay.getData().getUrlList().get(0).getDuration());
                                musicInfo.setAlbum(searchPlay.getData().getAlbumName());
                                musicInfos.add(musicInfo);
                                EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, searchPlay.getData().getName()));
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });
                volleySingleton.addQueue(stringRequestUtf);
                break;
            case R.id.recent_search_list: // 最近搜索
                RecentSearch recentSearch = (RecentSearch) parent.getItemAtPosition(position);
                String recent_search = recentSearch.getSearchTv();
                searchEdit.setText(recent_search);
                try {
                    endUrl = URLEncoder.encode(recent_search, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                SharedPreferencesUtils.putSharePre(SearchActivity.this, "SearchActivityEditText", "endUrl", endUrl);
                manager = getSupportFragmentManager();
                transaction = manager.beginTransaction();
                transaction.replace(R.id.search_below, searchResultFragment);
                transaction.commit();
                break;
        }
    }

    /**
     * 点击最近搜索删除按钮
     *
     * @param recentSearch 点击行布局返回的文字
     * @param position     当前点击的位置
     */
    @Override
    public void onClickDelete(RecentSearch recentSearch, int position) {
        daoSingleton.deleteRecentSearchByName(recentSearch.getSearchTv());
        adapter.deleteByPosition(position);
    }
}

